import { jwtVerify, decodeJwt } from 'jose';

// JWT密钥 - 应该与后端保持一致
const JWT_SECRET = process.env.JWT_SECRET || 'your-super-secret-jwt-key-change-in-production';

// JWT令牌接口
export interface JWTPayload {
  userId: string;
  username: string;
  role: string;
  iat?: number;
  exp?: number;
}

// 验证JWT令牌
export const verifyToken = async (token: string): Promise<JWTPayload | null> => {
  try {
    // 移除Bearer前缀
    const cleanToken = token.replace(/^Bearer\s/, '');
    
    // 创建密钥
    const secret = new TextEncoder().encode(JWT_SECRET);
    
    // 验证令牌
    const { payload } = await jwtVerify(cleanToken, secret);
    
    // 检查令牌是否过期
    if (payload.exp && Date.now() >= payload.exp * 1000) {
      console.warn('Token已过期');
      return null;
    }
    
    // 类型转换，确保包含我们需要的字段
    const jwtPayload: JWTPayload = {
      userId: payload.userId as string,
      username: payload.username as string,
      role: payload.role as string,
      iat: payload.iat as number,
      exp: payload.exp as number
    };
    
    return jwtPayload;
  } catch (error) {
    console.error('Token验证失败:', error);
    return null;
  }
};

// 生成JWT令牌（仅用于测试，生产环境应该由后端生成）
export const generateToken = async (payload: Omit<JWTPayload, 'iat' | 'exp'>): Promise<string> => {
  // 注意：jose库的jwtSign需要更复杂的设置，这里简化处理
  // 实际生产环境应该由后端生成令牌
  throw new Error('前端不应生成JWT令牌，请使用后端API');
};

// 检查令牌是否即将过期（提前5分钟）
export const isTokenExpiringSoon = (token: string): boolean => {
  try {
    const decoded = decodeJwt(token) as JWTPayload;
    if (!decoded.exp) return false;
    
    const now = Date.now() / 1000;
    const fiveMinutes = 5 * 60;
    
    return decoded.exp - now < fiveMinutes;
  } catch {
    return true;
  }
};

// 从Authorization header中提取令牌
export const extractTokenFromHeader = (authHeader: string | null): string | null => {
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return null;
  }
  
  return authHeader.substring(7);
};

// 验证用户权限
export const hasPermission = (userRole: string, requiredRoles: string[]): boolean => {
  return requiredRoles.includes(userRole);
};

// 检查是否是管理员
export const isAdmin = (userRole: string): boolean => {
  return userRole === 'ADMIN';
};

// 检查是否是普通用户
export const isUser = (userRole: string): boolean => {
  return userRole === 'USER';
};
